package edu.suda.xsap.controller;

import edu.suda.xsap.common.Result;
import edu.suda.xsap.dto.EmployeeDto;
import edu.suda.xsap.service.EmployeeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/employee")
@Slf4j
@Tag(name = "员工管理", description = "员工管理相关接口")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Operation(summary = "获取员工列表")
    @GetMapping("/list")
    public Result list(@RequestParam int page,
                       @RequestParam int size) {
        try {
            List<EmployeeDto> employeeDtos = employeeService.findAll(page, size);
            return Result.success(employeeDtos);
        } catch (Exception e) {
            log.error("查询失败", e);
            return Result.failure(e.getMessage(), e);
        }
    }


    @Operation(summary = "保存员工信息")
    @PostMapping("/save")
    public Result save(@RequestBody EmployeeDto employeeDto) {
        try {
            EmployeeDto savedEmployee = employeeService.save(employeeDto);
            return Result.success(savedEmployee);
        } catch (Exception e) {
            log.error("保存失败", e);
            return Result.failure(e.getMessage(), e);
        }
    }

    @Operation(summary = "更新员工信息")
    @PutMapping("/update")
    public Result update(@RequestBody EmployeeDto employeeDto) {
        try {
            if (employeeDto.getId() == null) {
                return Result.failure("ID不能为空");
            }
            EmployeeDto updatedEmployee = employeeService.update(employeeDto);
            return Result.success(updatedEmployee);
        } catch (Exception e) {
            log.error("更新失败", e);
            return Result.failure(e.getMessage(), e);
        }
    }

    @Operation(summary = "删除员工")
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        try {
            employeeService.delete(id);
            return Result.success();
        } catch (Exception e) {
            log.error("删除失败", e);
            return Result.failure(e.getMessage(), e);
        }
    }
}